package org.onvivals.app.modules.ums.controller;

import cn.hutool.core.bean.BeanUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.github.binarywang.wxpay.bean.order.WxPayMpOrderResult;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.onvivals.app.modules.auth.util.SaTokenUtil;
import org.onvivals.app.modules.ums.param.RechargeParam;
import org.onvivals.app.weixin.service.WeixinPayService;
import org.onvivals.common.enums.AppFromEnum;
import org.onvivals.common.enums.BillDetailEnum;
import org.onvivals.common.exception.BusinessException;
import org.onvivals.common.web.Result;
import org.onvivals.module.ums.entity.SysGroupData;
import org.onvivals.module.ums.entity.UmsUser;
import org.onvivals.module.ums.service.ISysGroupDataService;
import org.onvivals.module.ums.service.IUmsUserRechargeService;
import org.onvivals.module.ums.vo.SysGroupDataVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 * 用户充值 前端控制器
 * </p>
 */
@Slf4j
@RestController
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
@Tag(name = "小程序:用户充值")
@RequestMapping("/recharge")
public class UserRechargeController {

	private final IUmsUserRechargeService userRechargeService;
	private final ISysGroupDataService systemGroupDataService;
	private final WeixinPayService wxPayService;

	/**
	 * 小程序充值
	 */
	@PostMapping("/pay")
	@Operation(summary = "公众号充值/H5充值")
	public Result<Map<String, Object>> add(@Valid @RequestBody RechargeParam param) {
		UmsUser pmsMember = SaTokenUtil.getUser();
		Map<String, Object> map = new LinkedHashMap<>();
		map.put("type", param.getFrom());
		String price = "0.01";
		String giveIntegral = "1";
		String orderSn = userRechargeService.addRecharge(pmsMember, price, giveIntegral, "integral");
		if (AppFromEnum.ROUNTINE.getValue().equals(param.getFrom())) {
			WxPayMpOrderResult wxPayMpOrderResult = (WxPayMpOrderResult) wxPayService
					.unifyPay(orderSn, param.getFrom(), BillDetailEnum.TYPE_1.getValue(), "小程序充值");
			Map<String, String> jsConfig = new HashMap<>();
			jsConfig.put("timeStamp", wxPayMpOrderResult.getTimeStamp());
			jsConfig.put("appId", wxPayMpOrderResult.getAppId());
			jsConfig.put("paySign", wxPayMpOrderResult.getPaySign());
			jsConfig.put("nonceStr", wxPayMpOrderResult.getNonceStr());
			jsConfig.put("package", wxPayMpOrderResult.getPackageValue());
			jsConfig.put("signType", wxPayMpOrderResult.getSignType());
			map.put("data", jsConfig);
		}
		return Result.OK(map);
	}

	/**
	 * 会员充值方案
	 */
	@GetMapping("/vip/list")
	@Operation(summary = "会员充值方案")
	public Result<?> rechargeList() {
		List<SysGroupData> sysGroupDataList = systemGroupDataService.list(
				Wrappers.<SysGroupData>lambdaQuery()
						.eq(SysGroupData::getGroupName, "vip_price_ways")
						.eq(SysGroupData::getStatus, 1));
		List<SysGroupDataVo> systemGroupDataVoList = sysGroupDataList.stream().map(s -> {
			SysGroupDataVo systemGroupDataVo = new SysGroupDataVo();
			BeanUtil.copyProperties(s, systemGroupDataVo, "value");
			systemGroupDataVo.setValue(JSON.parseObject(s.getValue()));
			return systemGroupDataVo;
		}).collect(Collectors.toList());
		return Result.OK(systemGroupDataVoList);
	}

	/**
	 * 会员充值
	 */
	@PostMapping("/vip/pay")
	@Operation(summary ="会员充值")
	public Result<Map<String, Object>> vipPay(@Valid @RequestBody RechargeParam param) {
		UmsUser pmsMember = SaTokenUtil.getUser();
		Map<String, Object> map = new LinkedHashMap<>();
		map.put("type", param.getFrom());
		SysGroupData systemGroupData = systemGroupDataService.getById(param.getRecharId());
		if (systemGroupData == null) {
			throw new BusinessException("充值方案不存在");
		}
		JSONObject jsonObject = JSON.parseObject(systemGroupData.getValue());
		String price = jsonObject.getString("price");
		String name = jsonObject.getString("name");
		int time = jsonObject.getInteger("time");
		String orderSn = userRechargeService.addVipRecharge(pmsMember, price, name, "vip",time);
		if (AppFromEnum.ROUNTINE.getValue().equals(param.getFrom())) {
			WxPayMpOrderResult wxPayMpOrderResult = (WxPayMpOrderResult) wxPayService
					.unifyPay(orderSn, param.getFrom(), BillDetailEnum.TYPE_13.getValue(), "小程序开通会员");
			Map<String, String> jsConfig = new HashMap<>();
			jsConfig.put("timeStamp", wxPayMpOrderResult.getTimeStamp());
			jsConfig.put("appId", wxPayMpOrderResult.getAppId());
			jsConfig.put("paySign", wxPayMpOrderResult.getPaySign());
			jsConfig.put("nonceStr", wxPayMpOrderResult.getNonceStr());
			jsConfig.put("package", wxPayMpOrderResult.getPackageValue());
			jsConfig.put("signType", wxPayMpOrderResult.getSignType());
			map.put("data", jsConfig);
		}
		return Result.OK(map);
	}

}

